//
//  WeightsHistoryViewController.m
//  WeightMaster
//
//  Created by maoyu on 15/8/21.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "WeightsHistoryViewController.h"
#import "BDFoundation.h"
#import "WMModels.h"
#import "AutoMoodView.h"
#import "UIScrollView+TwitterCover.h"
#import "UIColor+WeightMaster.h"
#import <EXTScope.h>
#import <DateTools.h>
#import <Masonry.h>

#define COVER_HEIGHT    250*kScreen_Height/667.0

static NSString * const DefaultImageName = @"default_bg.jpg";

@interface WeightsHistoryViewController () {
    UIScrollView * _scrollView;
    UIView * _downArrowView;
    AutoMoodView * _moodView;
    UILabel * _daysDescriptionLabel;
    WeightsChartController * _weightsChart;
    
    UIButton * _setCoverButton;
    
    NSArray * _weights;
}

@end

@implementation WeightsHistoryViewController

#pragma 私有函数
- (void)createScrollView {
    _scrollView = [[UIScrollView alloc] init];
    [_scrollView setContentSize:CGSizeMake(kScreen_Width, kScreen_Height + 20)];
    _scrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_scrollView];
    @weakify(self)
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        make.edges.equalTo(self.view);
    }];
    
    [_scrollView addTwitterCoverWithImage:[UIImage imageNamed:@"default_bg.jpg"]];

    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, COVER_HEIGHT, kScreen_Width, kScreen_Height)];
    view.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:view];
    
    [self createMoodView];
}

- (void)createMoodView{
    _moodView = [[AutoMoodView alloc] init];
    [_scrollView addSubview:_moodView];
    
    @weakify(self);
    [_moodView mas_makeConstraints:^(MASConstraintMaker * maker){
        @strongify(self);
        maker.centerX.equalTo(self.view.mas_centerX);
        maker.centerY.equalTo(self.view.mas_top).offset(COVER_HEIGHT/2);
        maker.width.equalTo(self.view.mas_width);
        maker.height.equalTo(@(180));
    }];
}

- (void)createDownArrowLayer {
    UIBezierPath * path = [UIBezierPath bezierPath];
    CGFloat arrowH = 8.0;
    CGFloat arrowW = 20;
    CGFloat arrowY = COVER_HEIGHT + 5;
    [path moveToPoint:CGPointMake(0, 3)];
    [path addLineToPoint:CGPointMake(arrowW/2,arrowH)];
    [path addLineToPoint:CGPointMake(arrowW,3)];
    path.lineWidth = 2.0;
    
    CAShapeLayer * downArrowLayer = [[CAShapeLayer alloc] init];
    downArrowLayer.path = [path CGPath];
    downArrowLayer.strokeColor = [RGB(134, 134, 149) CGColor];
    downArrowLayer.fillColor = [[UIColor clearColor] CGColor];
    
    _downArrowView = [[UIView alloc] init];
    [_scrollView addSubview:_downArrowView];
    [_downArrowView mas_makeConstraints:^(MASConstraintMaker * maker) {
        maker.centerX.equalTo(_scrollView);
        maker.top.mas_equalTo(arrowY);
        maker.width.mas_equalTo(arrowW);
        maker.height.mas_equalTo(arrowW);
    }];
    
    [_downArrowView.layer addSublayer:downArrowLayer];
}

- (void)createWeightsChart{
    _weightsChart = [[WeightsChartController alloc] init];
    _weightsChart.shouldShowDates = YES;
    _weightsChart.shouldShowSelectionState = YES;
    _weightsChart.delegate = self;
    [_scrollView addSubview:_weightsChart.containerView];
    
    [_weightsChart.containerView mas_makeConstraints:^(MASConstraintMaker * maker){
        maker.leading.equalTo(self.view.mas_leading);
        maker.trailing.equalTo(self.view.mas_trailing);
        maker.top.equalTo(@(COVER_HEIGHT + 22));
        maker.height.equalTo(@(161));
    }];
    
    _weightsChart.items = [[WMDataCache sharedInstance] weights];
}

- (void)refreshCoverImageWithWMWeight:(WMWeight *)weight {
    if (weight.profileImage) {
        _setCoverButton.hidden = NO;
        _moodView.hidden = YES;
        _scrollView.twitterCoverView.image = weight.profileImage;
    }else {
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[_weightsChart indexOfItemForWeight:weight] inSection:0];
        WMMood mood = [_weightsChart moodForWeight:weight atIndexPath:indexPath];
        
        _setCoverButton.hidden = YES;
        _moodView.hidden = NO;
        [_moodView resetContentWithMood:mood];
        
        _scrollView.twitterCoverView.image = [UIImage imageNamed:DefaultImageName];        
    }
}

- (void)createDaysView {
    _daysDescriptionLabel = [[UILabel alloc] init];
    _daysDescriptionLabel.font = [UIFont systemFontOfSize:13];
    _daysDescriptionLabel.textColor = RGB(117, 117, 132);
    _daysDescriptionLabel.text = @"记录天数";
    _daysDescriptionLabel.textAlignment = NSTextAlignmentCenter;
    [_scrollView addSubview:_daysDescriptionLabel];
    CGFloat offset = 50;
    if (iPhone4) {
        offset = 0;
    }else if (iPhone5) {
        offset = 20;
    }
    @weakify(self)
    [_daysDescriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        make.centerX.equalTo(self->_scrollView);
        make.top.equalTo(_weightsChart.containerView.mas_bottom).offset(offset);
    }];
    
    UILabel * daysLabel = [[UILabel alloc] init];
    daysLabel.textColor =  RGB(32, 32, 47);
    daysLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:30.0];
    daysLabel.text = [NSString stringWithFormat:@"%ld",(long)[[WMDataCache sharedInstance].weights count]];
    daysLabel.textAlignment = NSTextAlignmentCenter;
    [_scrollView addSubview:daysLabel];
    [daysLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        make.centerX.equalTo(self->_daysDescriptionLabel);
        make.top.equalTo(self->_daysDescriptionLabel.mas_bottom).offset(5);
    }];
}

- (void)createMinWeightView {
    UILabel *  weightDescriptionLabel = [[UILabel alloc] init];
    weightDescriptionLabel.font = [UIFont systemFontOfSize:13];
    weightDescriptionLabel.textColor =  RGB(117, 117, 132);
    weightDescriptionLabel.text = @"最低体重";
    _daysDescriptionLabel.textAlignment = NSTextAlignmentCenter;
    [_scrollView addSubview:weightDescriptionLabel];
    @weakify(self)
    [weightDescriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        make.trailing.equalTo(self->_daysDescriptionLabel.mas_leading).offset(-27);
        make.top.equalTo(self->_daysDescriptionLabel.mas_bottom).offset(50);
    }];
    
    WMWeight * weight = [self getMinWeight];
    if (weight) {
        UILabel * dateLabel = [[UILabel alloc] init];
        dateLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:12.0];
        dateLabel.text = [weight monthAndDayString];//[weight.measuringDate formattedDateWithFormat:@"MM.dd"];
        dateLabel.textAlignment = NSTextAlignmentCenter;
        [_scrollView addSubview:dateLabel];
        [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weightDescriptionLabel);
            make.top.equalTo(weightDescriptionLabel.mas_bottom).offset(5);
        }];
        
        
        UILabel * weightLabel = [[UILabel alloc] init];
        weightLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:30.0];
        weightLabel.textColor =  RGB(32, 32, 47);
        weightLabel.text = [WMHelper stringValueForWeight:weight.value withUnit:[WMAppSetting sharedInstance].weightUnit];
        weightLabel.textAlignment = NSTextAlignmentCenter;
        [_scrollView addSubview:weightLabel];
        [weightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weightDescriptionLabel);
            make.top.equalTo(dateLabel.mas_bottom).offset(5);
        }];

    }
}

- (void)createMaxWeightView {
    UILabel *  weightDescriptionLabel = [[UILabel alloc] init];
    weightDescriptionLabel.font = [UIFont systemFontOfSize:13];
    weightDescriptionLabel.textColor =  RGB(117, 117, 132);
    weightDescriptionLabel.text = @"最高体重";
    _daysDescriptionLabel.textAlignment = NSTextAlignmentCenter;
    [_scrollView addSubview:weightDescriptionLabel];
    @weakify(self)
    [weightDescriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        make.leading.equalTo(self->_daysDescriptionLabel.mas_trailing).offset(27);
        make.top.equalTo(self->_daysDescriptionLabel.mas_bottom).offset(50);
    }];
    
    WMWeight * weight = [self getMaxWeight];
    if (weight) {
        UILabel * dateLabel = [[UILabel alloc] init];
        dateLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:12.0];
        dateLabel.text = [weight monthAndDayString];
        dateLabel.textAlignment = NSTextAlignmentCenter;
        [_scrollView addSubview:dateLabel];
        [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weightDescriptionLabel);
            make.top.equalTo(weightDescriptionLabel.mas_bottom).offset(5);
        }];
        
        UILabel * weightLabel = [[UILabel alloc] init];
        weightLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:30.0];
        weightLabel.textColor =  RGB(32, 32, 47);
        weightLabel.text = [WMHelper stringValueForWeight:weight.value withUnit:[WMAppSetting sharedInstance].weightUnit];
        weightLabel.textAlignment = NSTextAlignmentCenter;
        [_scrollView addSubview:weightLabel];
        [weightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weightDescriptionLabel);
            make.top.equalTo(dateLabel.mas_bottom).offset(5);
        }];
    }
}

- (WMWeight *)getMinWeight {
    WMWeight * weight = nil;
    if (nil != _weights) {
        return [_weights objectAtIndex:0];
    }
    return weight;
}

- (WMWeight *)getMaxWeight {
    WMWeight * weight = nil;
    if (nil != _weights) {
        if (1 == [_weights count]) {
            weight = [_weights objectAtIndex:0];
        }else {
            weight = [_weights objectAtIndex:1];
        }
    }
    return weight;
}

- (void)createSetCoverView {
    const CGFloat width = 80.0;
    const CGFloat hight = 25.0;
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, hight)];
    [button setTitle:@"设为封面" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [button setTitleColor:[UIColor mainColor] forState:UIControlStateNormal];
    [button makeCornorRadius:13.0];
    [button addBorderWithWidth:1 withColor:[UIColor mainColor]];
    [button addTarget:self action:@selector(setCoverImage) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:button];
    @weakify(self)
    [button mas_makeConstraints:^(MASConstraintMaker * make) {
        @strongify(self)
        make.trailing.equalTo(self.view.mas_trailing).offset(-15);
        make.top.equalTo(self.view.mas_top).offset(25);
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(hight);
    }];
    
    _setCoverButton = button;
}

- (void)setCoverImage {
    [[WMAppSetting sharedInstance] setCoverImage:_scrollView.twitterCoverView.image];
    [[MBProgressManager defaultManager] showSuccessMessage:@"设置成功"];
}

#pragma 事件函数
- (void)viewDidLoad {
    self.view.backgroundColor = [UIColor whiteColor];
    _weights = [[WMDataCache sharedInstance] minAndMaxWeightObjects:nil];

    [self createScrollView];
    [self createSetCoverView];
    [self createDownArrowLayer];
    [self refreshCoverImageWithWMWeight:[WMDataCache sharedInstance].latestWeight];
    
    [self createWeightsChart];
    [self createDaysView];
    [self createMinWeightView];
    [self createMaxWeightView];
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [_weightsChart moveToRightestItem];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Weights Chart delegate
- (void)weightsChartController:(WeightsChartController *)controller didTouchedImageAtWeightItem:(WMWeight *)weight{
    NSLog(@"选择的体重日期：%@", [weight monthAndDayString]);

    [self refreshCoverImageWithWMWeight:weight];
}

- (void)didTouchedWeightsChartController:(WeightsChartController *)controller withWeight:(WMWeight *)weight{
    if (weight) {
        [self refreshCoverImageWithWMWeight:weight];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end